package com.atguigu.gulimall.product.service.impl;

import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;
import com.atguigu.gulimall.product.dao.CategoryDao;
import com.atguigu.gulimall.product.entity.CategoryEntity;
import com.atguigu.gulimall.product.service.CategoryBrandRelationService;
import com.atguigu.gulimall.product.service.CategoryService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

    @Autowired
    CategoryBrandRelationService categoryBrandRelationService;
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<CategoryEntity> listWithTree() {
        //1.查出所有分类
        List<CategoryEntity> categoryEntities = baseMapper.selectList(null);
        //2.找出一级分类
        List<CategoryEntity> rootList = categoryEntities.stream()
                .filter((t) -> t.getCatLevel() == 1)
                .map((menu) -> {
                    List<CategoryEntity> children = getChildren(menu, categoryEntities);
                    menu.setChildren(children);
                    return menu;
                })
                .sorted(Comparator.comparingInt(CategoryEntity::getSort))
                .collect(Collectors.toList());


        //2.组装树形结构
        return rootList;
    }

    @Override
    public void removeMenuByIds(List<Long> asList) {
        //TODO 检查当前删除的菜单是否被其他地方引用
        //使用逻辑删除
        baseMapper.deleteBatchIds(asList);
    }

    @Override
    public Long[] getCatelogPath(Long catelogId) {
        //拿到三级分类的对象
//        CategoryEntity categoryEntity = baseMapper.selectById(catelogId);
        //三级分类的catID 是路径最后一个ID
//        Long catId3 = categoryEntity.getCatId();
        //父id是第二个路径
//        Long catId2 = categoryEntity.getParentCid();
        //第一个路径
//        CategoryEntity categoryEntity1 = baseMapper.selectById(catId2);
//        Long catId1 = categoryEntity1.getCatId();
//        return new long[]{catId1,catId2,catId3};
//======================================================================
        //用递归查出所有父节点的ID
        List paths = new ArrayList();
        List parentId = findParentId(paths, catelogId);
        Long[] d = new Long[parentId.size()];
        return (Long[]) parentId.toArray(d);
    }

    @Transactional
    @Override
    public void updateCategory(CategoryEntity category) {
        this.updateById(category);
        if (StringUtils.isNotBlank(category.getName())) {
            categoryBrandRelationService.updateCategory(category.getCatId(), category.getName());
        }

    }


    /**
     * 递归查找父类id的方法
     */
    private List<Long> findParentId(List<Long> paths,long catelogId) {
        //获取当前菜单实例
        CategoryEntity currentCategory = this.getById(catelogId);
        paths.add(catelogId);
        if (0 != currentCategory.getParentCid()) {
            findParentId(paths, currentCategory.getParentCid());
        }

        return paths;
    }

    //递归查找子类的方法
    private List<CategoryEntity> getChildren(CategoryEntity root, List<CategoryEntity> categoryEntities) {
        List<CategoryEntity> childrenList = categoryEntities.stream()
                .filter((e) -> root.getCatId() == e.getParentCid())
                .map((e1) -> {
                    e1.setChildren(getChildren(e1, categoryEntities));
                    return e1;
                })
                .collect(Collectors.toList());
        return childrenList;
    }

}